#!/bin/bash
#description: auto install cobbler enviroment on centos7.4
StartIP="192.168.201.50"
StopIP="192.168.201.200"
NET="192.168.201.0"
MASK="255.255.255.0"
ROUTERIP="192.168.201.1"
DNS1="202.96.209.133"
TFTPIP="192.168.201.10"
HTTPIP="192.168.201.10"
SERVERIP="192.168.201.10"
DOMAIN="51yuki.cn"


function init(){
        #最小化安装系统，需要安装如下包
        yum -y install vim rsync net-tools wget tree gcc gcc-c++ openssh-clients autoconf make lrzsz ntpdate
        #配置epel源
        cd /etc/yum.repos.d/
        [ ! -f epel.repo ] && yum -y install https://mirrors.aliyun.com/epel/epel-release-latest-7.noarch.rpm
        #关闭防火墙
        systemctl disable firewalld
        systemctl stop firewalld
        sed -i "s/SELINUX=permissive/SELINUX=disabled/g" /etc/selinux/config
        setenforce 0
        #配置时间同步
        /sbin/ntpdate time1.aliyun.com
}

function dhcp(){
        #安装dhcp服务
        yum -y install dhcp
        #配置dhcp服务
        cat > /etc/dhcp/dhcpd.conf <<EDF
        # option definitions common to all supported networks...
        option domain-name "$DOMAIN";
        option domain-name-servers $DNS1;
        default-lease-time 43200;
        max-lease-time 86400;
        log-facility local7;
        subnet $NET netmask $MASK {
                range $StartIP $StopIP;
                option subnet-mask $MASK;
                option routers $ROUTERIP;
                option domain-name-servers $DNS1;
                default-lease-time 21600;
                max-lease-time 43200;
		filename "pexlinux.0";
		next-server $TFTPIP;
        }
EDF
#启动dhcp服务
systemctl enable dhcpd
systemctl start dhcpd
if [ "`ss -tunlp|grep 67|awk -F: '{print $2}'|awk '{print $1}'`" == "67" ];then
                echo "dhcp server start succfull"
else    
                echo "dhcp server start fail"
                exit 1
fi
}
function tftp(){
        #安装tftp服务
        yum install tftp-server -y
        #安装syslinux
        yum -y install syslinux
        #启动tftp服务
        systemctl enable tftp
        systemctl start tftp
}
function cobbler() {
	#安装cobbler
	yum -y install cobbler cobbler-web pykickstart debmirror httpd	
	systemctl enable cobblerd
	systemctl start cobblerd
	systemctl enable httpd
	systemctl start httpd
	#备份settings文件
	cp /etc/cobbler/settings{,.ori_$(date +%F)}
	#修改配置settings
	sed -i "s/server: 127.0.0.1/server: ${SERVERIP}/" /etc/cobbler/settings
	sed -i "s/next_server: 127.0.0.1/server: ${SERVERIP}/" /etc/cobbler/settings
	sed -ri "/default_password_crypted/s#(.*: ).*#\1\"`openssl passwd -1 -salt 'testyu' 'Aa123321'`\"#" /etc/cobbler/settings
	sed -i "s/manage_dhcp: 0/manage_dhcp: 1/" /etc/cobbler/settings
	sed -i "s/pxe_just_once: 0/pxe_just_once: 1/" /etc/cobbler/settings
	sed -i.ori "s#192.168.1#192.168.201#g" /etc/cobbler/dhcp.template
	#修改tftp
	sed -i "s#yes#no#g" /etc/xinetd.d/tftp
	#启动rsyncd
	systemctl enable rsyncd && systemctl start rsyncd
	#修改debmirror.conf
	sed -i "s/^@dists/#&/g" /etc/debmirror.conf
	sed -i "s/^@arches/#&/g" /etc/debmirror.conf
	#同步cobbler
	/usr/bin/cobbler sync
	#启动cobbler
	systemctl restart cobblerd
}
function cobbler_system(){
	read -p "please input system version <CentOS7.4_x86_64|Ubuntu16.04-x86_64>:" system
	if [ ! -d /mnt/cdrom ];then
		mkdir /mnt/cdrom
		mount /dev/cdrom /mnt/cdrom
	else
	         umount /mnt/cdrom
		mount /dev/cdrom /mnt/cdrom
	fi
	
	if [ $? -ne 0 ];then
		echo "Please mount the DVD"
		exit 1
	fi
	/usr/bin/cobbler import --name=$system --path=/mnt/cdrom
	
	if [[ $system =~ ^CentOS7 || $system =~ ^centos7 ]];then
		cat > /var/lib/cobbler/kickstarts/centos7.cfg <<EDF
#version=DEVEL
#Install OS instead of upgrade
install
# X Windows system configuration information
xconfig --startxonboot
# Keyboard layouts
keyboard --vckeymap=us --xlayouts='us'
#Reboot after installation
reboot
# System authorization information
auth --enableshadow --passalgo=sha512
# Root password
rootpw --iscrypted \$6\$mvLkrJbn.KQCw.Ev\$KjLKoHjWoqG1mmDdMd73MiCIe4Z8lDK42n.rHLLLYkoINqaXUJzkGGJFzvXp8.JdTaEPjXY1NZIIj4tw8WQn80
#create user admin
user --name=admin --password=\$6\$SZtk92AfcisRCCYEi\$Oli2yz8zhGNCpHmD2GAqXYFd50kflw7AzVn8Xr5RW9kSi6pP9oS1OKKdrvXKhhmEeXqDfAuMZ3A0h6nYF62kg/ --iscrypted --gecos="admin"
# System timezone
timezone Asia/Shanghai --isUtc --nontp
#Use network install
url --url="http://$HTTPIP/cobbler/ks_mirror/$system/"
# System language
lang en_US.UTF-8
#Use graphical install
text
#firewall configuration
firewall --disabled
# Network information
network  --bootproto=dhcp --device=eth0 --onboot=yes --noipv6 --activate
# Use test mode install
firstboot --disable
#SElinux configuration
selinux --permissive
# System bootloader configuration
ignoredisk --only-use=sda
zerombr
bootloader --append=" crashkernel=auto" --location=mbr --boot-drive=sda
clearpart --all --initlabel
#Disk partitioning information
autopart --type=lvm
%packages
@^minimal
@core
@development
@compat-libraries
kexec-tools
gcc
gcc-c++
autoconf
make
openssh-clients
sysstat
tree
lrzsz
dos2unix
wget
net-tools
vim
curl
bash-completion
%end
%post 
	systemctl disable postfix.service   
%end
EDF
		/usr/bin/cobbler profile add --name=$system-server --distro=$system --kickstart=/var/lib/cobbler/kickstarts/centos7.cfg 
	elif [[ $system =~ ^CentOS6 || $system =~ ^centos6 ]];then
	  	cat > /var/lib/cobbler/kickstarts/centos6.cfg <<EOF
on=DEVEL
#Firewall configuration
firewall --disabled
#Install OS instead of upgrade
install
#Use network install
url --url="http://$HTTPIP/cobbler/ks_mirror/$system/"
# Root password
rootpw --iscrypted \$6\$mvLkrJbn.KQCw.Ev\$KjLKoHjWoqG1mmDdMd73MiCIe4Z8lDK42n.rHLLLYkoINqaXUJzkGGJFzvXp8.JdTaEPjXY1NZIIj4tw8WQn80
# System authorization information
auth --enableshadow --passalgo=sha512
#Use text install
text
firstboot --disable
# Keyboard layouts
keyboard us
#System language
lang en_US
#Reboot after installation
reboot
# System timezone
timezone Asia/Shanghai

# System language
lang en_US.UTF-8

#System bootloader configation
bootloader --location=mbr --driveorder=sda --append="crashkernel=auto rhgb quiet"
#clear the master boot record
zerombr
#SElinux configuration
selinux --disabled
# System bootloader configuration
ignoredisk --only-use=sda
clearpart --all --initlabel
#Disk partitioning information
part /boot --fstype ext4 --size 500 
part swap --size 2048
part / --fstype ext4 --size 1 --grow

%packages
@core
@development
@compat-libraries
kexec-tools
gcc
gcc-c++
autoconf
make
openssh-clients
sysstat
tree
lrzsz
dos2unix
wget
net-tools
vim
curl
%end
%post
	systemctl disable postfix.service
%end
EOF

 		/usr/bin/cobbler profile add --name=$system-server --distro=$system --kickstart=/var/lib/cobbler/kickstarts/centos6.cfg
	elif [[ $system =~ ^Ubuntu || $system =~ ^ubuntu ]];then
		  cat >/var/lib/cobbler/kickstarts/ubuntu.send <<EOF 
d-i debian-installer/locale string en_US
d-i console-setup/ask_detect boolean false
d-i keyboard-configuration/toggle select No toggling
d-i keyboard-configuration/layoutcode string us
d-i keyboard-configuration/variantcode string
d-i netcfg/choose_interface select auto
d-i netcfg/get_hostname string  $myhostname
d-i netcfg/get_domain string $myhostname
d-i time/zone string Asia/shanghai
d-i clock-setup/utc boolean true
d-i clock-setup/ntp boolean true
d-i mirror/country string manual
d-i mirror/http/hostname string $HTTPIP
d-i mirror/http/directory string /cobbler/ks_mirror/$system/
d-i mirror/http/proxy string
d-i live-installer/net-image string http://$HTTPIP/cobbler/links/$system/install/filesystem.squashfs
d-i partman/choose_partition select finish
d-i partman/confirm boolean true
d-i partman/confirm_nooverwrite boolean true
d-i partman-auto/method string lvm
d-i partman-lvm/device_remove_lvm boolean true
d-i partman-lvm/confirm boolean true
d-i partman-lvm/confirm_nooverwrite boolean true
d-i partman-md/device_remove_md boolean true
d-i partman-partitioning/confirm_write_new_label boolean true
d-i partman-auto/choose_recipe select atomic
d-i passwd/root-login boolean false
d-i passwd/root-password-crypted password \$6\$mvLkrJbn.KQCw.Ev\$KjLKoHjWoqG1mmDdMd73MiCIe4Z8lDK42n.rHLLLYkoINqaXUJzkGGJFzvXp8.JdTaEPjXY1NZIIj4tw8WQn80
d-i passwd/make-user boolean true
d-i passwd/user-fullname string www
d-i passwd/username string www
d-i passwd/user-password password Aa@123456
d-i passwd/user-password-again password Aa@123456
d-i user-setup/allow-password-weak boolean true
d-i user-setup/encrypt-home boolean false
\$SNIPPET('preseed_apt_repo_config')
tasksel tasksel/first multiselect standard
d-i pkgsel/include string ntp ssh wget openssh-server
# Debian needs this for the installer to avoid any question for grub
# Please verify that it suit your needs as it may overwrite any usb stick
#if $breed == "debian"
d-i grub-installer/grub2_instead_of_grub_legacy boolean true
d-i grub-installer/bootdev string default
#end if

# Use the following option to add additional boot parameters for the
# installed system (if supported by the bootloader installer).
# Note: options passed to the installer will be added automatically.
#d-i debian-installer/add-kernel-opts string $kernel_options_post

# Avoid that last message about the install being complete.
d-i finish-install/reboot_in_progress note

EOF
		/usr/bin/cobbler profile add --name=$system-server --distro=$system --kickstart=/var/lib/cobbler/kickstarts/ubuntu.send
else
	echo "This script is only suitable for centos and ubuntu systems"
	exit 3
fi
	cobbler sync
	systemctl restart cobblerd
}
function install_cobbler(){
	init
	dhcp
	tftp
	cobbler
}
DATE=$(date +%F)
KERNEL_VERSION=$(uname -r)
HOSTNAME=$(hostname)
cat <<EOF
-----------------------------------------------------------------
                auto Install and configure cobbler
----------------------------------------------------------------
| DATE                   :  $DATE
| IP                     :  $SERVERIP
| KERNEL_VERSION         :  ${KERNEL_VERSION}
| HOSTNAME               :  $HOSTNAME
---------------------------------------------------------------
|*********Please Enter your Choice:***************************|
(1) Automatic install cobbler
(2) Automatic import linux system
(3) quit
EOF
read -p "please enter your choice:" input
case $input in
1)
   install_cobbler
   ;;
2)
   cobbler_system
   ;;
3)
  exit 4
esac

